import {
  changeProfile,
  getProfileUse,
  updatePhoto,
} from '@/store/actions/profile';
import { Button, List, DatePicker, NavBar, Popup, Toast } from 'antd-mobile';
import classNames from 'classnames';
import { useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import EditInput from './EditInput';
import EditList from './EditList';
import styles from './index.module.scss';
import moment from 'moment';
import { Dialog } from 'antd-mobile';
import { removeToken } from '@/store/actions/login';
import { useInitialState } from '@/utils/hooks';
const Item = List.Item;

const Edit = () => {
  const history = useHistory();
  const inputRef = useRef<HTMLInputElement>(null);
  //定义数据type的类型
  type inputType = {
    visible: boolean;
    type: '' | 'name' | 'intro';
  };
  type listType = {
    type: '' | 'photo' | 'gender';
    visible: boolean;
  };
  const dispatch = useDispatch();
  const { profileUse } = useInitialState(getProfileUse, 'profile');
  // 定义初始值,控制弹出层的显示
  const [inputValue, setInputValue] = useState<inputType>({
    visible: false,
    type: '',
  });
  // 定义初始值,控制底部弹出层的显示
  const [listValue, setListValue] = useState<listType>({
    visible: false,
    type: '',
  });
  // 定义方法,控制弹出层的隐藏
  const hideInput = () => {
    setInputValue({ visible: false, type: '' });
  };
  // 定义方法,控制底部弹出层关闭
  const hideList = () => {
    setListValue({
      visible: false,
      type: '',
    });
  };
  // 监听input选择图片事件
  const changePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      const file = e.target.files[0];
      const fd = new FormData();
      fd.append('photo', file);
      //发送请求,更新图片信息
      await dispatch(updatePhoto(fd));
      //给消息提示
      Toast.show({
        content: '修改成功',
        icon: 'success',
      });
      //关闭底部弹框
      hideList();
    }
  };
  // 控制日期框的状态
  const [pickerValue, setPickerValue] = useState(false);
  const updateTime = async (value: Date) => {
    //获取到数据,发送请求
    await Update('birthday', moment(value).format('YYYY-MM-HH'));
    setPickerValue(false);
  };

  const Update = async (key: string, value: string) => {
    //如果是图片,需要另外处理数据,因为图片需要的格式是fd
    if (key === 'photo') {
      inputRef.current?.click();
      return;
    }
    //发起请求获取到数据===>参数是子组件传递过来
    await dispatch(changeProfile({ [key]: value }));
    //修改成功后的消息提示
    Toast.show({
      content: '修改成功',
      icon: 'success',
    });
    //关闭右侧弹出层
    hideInput();
    // 关闭左侧弹出层
    hideList();
    // 重新获取数据,因为组件没有销毁和刷新===>在数据更新的action中直接完成
  };
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          style={{
            '--border-bottom': '1px solid #F0F0F0',
          }}
          onBack={() => history.go(-1)}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img width={24} height={24} src={profileUse.photo} alt="" />
                </span>
              }
              arrow
              onClick={() => {
                setListValue({
                  type: 'photo',
                  visible: true,
                });
              }}
            >
              头像
            </Item>
            <Item
              arrow
              extra={profileUse.name}
              onClick={() => setInputValue({ visible: true, type: 'name' })}
            >
              昵称
            </Item>
            <Item
              arrow
              onClick={() => setInputValue({ visible: true, type: 'intro' })}
              extra={
                <span className={classNames('intro', 'normal')}>
                  {profileUse.intro}
                </span>
              }
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              arrow
              extra={profileUse.gender === 0 ? '男' : '女'}
              onClick={() =>
                setListValue({
                  type: 'gender',
                  visible: true,
                })
              }
            >
              性别
            </Item>
            <Item
              arrow
              extra={profileUse.birthday}
              onClick={() => setPickerValue(true)}
            >
              生日
            </Item>
          </List>

          <DatePicker
            visible={pickerValue}
            value={new Date(profileUse.birthday)}
            title="选择年月日"
            min={new Date('1900-01-01')}
            max={new Date()}
            onCancel={() => setPickerValue(false)}
            onConfirm={updateTime}
          />
        </div>

        <div className="logout">
          <Button
            className="btn"
            onClick={() => {
              Dialog.show({
                title: '温馨提示',
                content: '确认退出吗',
                closeOnAction: true,
                actions: [
                  [
                    {
                      key: 'cancel',
                      text: '取消',
                      style: { color: 'skyblue' },
                    },
                    {
                      key: 'delete',
                      text: '确认',
                      style: { color: 'orange' },
                      onClick() {
                        // 1.清除toke 2.跳转页面
                        dispatch(removeToken());
                        history.replace('/login');
                      },
                    },
                  ],
                ],
              });
            }}
          >
            退出登录
          </Button>
        </div>
      </div>
      {/* 输入框弹出层 */}
      <Popup
        visible={inputValue.visible}
        position="right"
        bodyStyle={{ minWidth: '100vw' }}
        destroyOnClose
      >
        <EditInput
          hideInput={hideInput}
          type={inputValue.type}
          Update={Update}
        ></EditInput>
      </Popup>
      {/* 修改头像和性别弹出层 */}
      <Popup
        visible={listValue.visible}
        position="bottom"
        onMaskClick={() => {
          setListValue({ type: '', visible: false });
        }}
        bodyStyle={{ minHeight: '25vh' }}
      >
        <EditList
          type={listValue.type}
          Update={Update}
          hideList={hideList}
        ></EditList>
      </Popup>
      {/*定义输入框,用来选择图片文件  */}
      <input type="file" hidden ref={inputRef} onChange={changePhoto}></input>
    </div>
  );
};

export default Edit;
